package org.khd.auth.service.impl;

import org.khd.auth.domain.Permission;
import org.khd.auth.domain.Role;
import org.khd.auth.domain.RolePermission;
import org.khd.auth.dto.RoleDto;
import org.khd.auth.mapper.PermissionMapper;
import org.khd.auth.mapper.RolePermissionMapper;
import org.khd.auth.service.IRoleService;
import org.khd.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author saber
 * @since 2024-04-08
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void addOrUpdate(RoleDto roleDto) {
        Role role = roleDto.getRole();
        if (role.getId() != null){
            super.update(role);
        }else {
            super.add(role);
        }

        //维护中间表数据
        /*
        * 新增数据：新增数据和选择的权限数据写入到关联表
        * 修改数据：将原来的数据全部删除，再重新维护关联关系
        * */
        //1.删除角色对应的权限数据
        rolePermissionMapper.deleteById(role.getId());

        //2.重新维护关联关系
        //2.1 查询出用户选择的权限id的数据
        List<Permission> permissions = permissionMapper.queryByIds(roleDto.getPermissionIds());
        List<RolePermission> list = new ArrayList<>();

        for (Permission permission : permissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setPermissionSn(permission.getSn());
            list.add(rolePermission);
        }

        rolePermissionMapper.batchSave(list);

    }

    @Override
    public List<Long> getPermissionById(Long id) {
        return rolePermissionMapper.getPermissionById(id);
    }
}
